package com.china08.yxyapi.service.manage.tec.teaching.homework.impl;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import com.china08.yxyapi.api.manage.tec.teaching.homework.uploadques.homeworkUploadJieDaController.QuestionJieDaUploadModel;
import com.china08.yxyapi.api.manage.tec.teaching.homework.uploadques.homeworkUploadTianKongController.QuestionTianKongUploadModel;
import com.china08.yxyapi.api.manage.tec.teaching.homework.uploadques.homeworkUploadXuanzeController.ChooseModel;
import com.china08.yxyapi.api.manage.tec.teaching.homework.uploadques.homeworkUploadXuanzeController.QuestionDanXuanUploadModel;
import com.china08.yxyapi.entity.db.yxy.YxyQuesKnow;
import com.china08.yxyapi.entity.mg.res.AllTemplate;
import com.china08.yxyapi.entity.mg.res.YxyResQues;
import com.china08.yxyapi.repository.db.YxyQuesKnowRepository;
import com.china08.yxyapi.repository.mg.YxyResQuesRepository;
import com.china08.yxyapi.service.manage.tec.teaching.homework.HomeworkQuestionUploadService;
import com.china08.yxyapi.util.EsQuestionUpdateUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.dataformat.xml.JacksonXmlModule;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;

@Service
public class HomeworkQuestionUploadServiceImpl implements HomeworkQuestionUploadService {

    @Autowired
    private YxyResQuesRepository yxyResQuesRepository;

    @Autowired
    private YxyQuesKnowRepository yxyQuesKnowRepository;

    private YxyResQues getYxyResQues(String quesId, String userId, String quesType, String phase, String subject) {
        YxyResQues yxyResQues = null;
        if (StringUtils.isNotBlank(quesId)) {
            // 做修改的
            yxyResQues = yxyResQuesRepository.findById(quesId);
            Assert.notNull(yxyResQues, "试题未找到");
            Timestamp timestamp = new Timestamp(System.currentTimeMillis());
            yxyResQues.setModified(timestamp);
            yxyResQues.setModifiedBy(userId);
            Assert.isTrue(StringUtils.equals(yxyResQues.getQuestionType().trim(), quesType.trim()), "试题类型不容修改");
            Assert.isTrue(StringUtils.equals(yxyResQues.getPhase().trim(), phase.trim()), "学段不容修改");
            Assert.isTrue(StringUtils.equals(yxyResQues.getSubject().trim(), subject.trim()), "学科不容修改");
        } else {
            yxyResQues = new YxyResQues();
            Timestamp timestamp = new Timestamp(System.currentTimeMillis());
            yxyResQues.setCreated(timestamp);
            yxyResQues.setModified(timestamp);
            yxyResQues.setCreatedBy(userId);
            yxyResQues.setModifiedBy(userId);
            yxyResQues.setQuestionType(quesType);
            yxyResQues.setPhase(phase);
            yxyResQues.setSubject(subject);
        }
        Assert.isTrue(StringUtils.equals(userId, yxyResQues.getCreatedBy()), "只能对自己的试题操作");
        yxyResQues.setViewScope(0);
        return yxyResQues;
    }

    @Override
    public String uploadXuanze(QuestionDanXuanUploadModel questionUploadModel) throws JsonProcessingException {
        String body = getBodyDanxuan(questionUploadModel);
        String quesId = questionUploadModel.id;
        YxyResQues yxyResQues = getYxyResQues(quesId, questionUploadModel.userId, questionUploadModel.questionType,
                questionUploadModel.phase, questionUploadModel.subject);
        // 知识点
        List<Integer> knowIds = questionUploadModel.knowList.stream().map(x -> x.id).collect(Collectors.toList());
        List<YxyQuesKnow> knows = yxyQuesKnowRepository.findByIdIn(knowIds);
        String knowledgeText = "";
        String knowledgeFullidsString = "";
        for (YxyQuesKnow knowledge : knows) {
            knowledgeText += ("," + knowledge.getName());
            knowledgeFullidsString += ("|" + knowledge.getFullPath());
        }

        yxyResQues.setBody(body);
        yxyResQues.setKnowledgeTexts(knowledgeText);

        List<String> strKnowIds = knowIds.stream().map(x -> x + "").collect(Collectors.toList());
        String strKnowId = StringUtils.join(strKnowIds, ",");
        yxyResQues.setKnowledgeIds(strKnowId);
        yxyResQues.setKnowFullIds(knowledgeFullidsString);

        yxyResQues.setDifficultyLevel(questionUploadModel.difficultyLevel);

        yxyResQues.setSrcType(questionUploadModel.srcType);
        if ("1".equals(questionUploadModel.difficultyLevel)) {
            yxyResQues.setDifficultyXishu(0.75F);
        } else if ("2".equals(questionUploadModel.difficultyLevel)) {
            yxyResQues.setDifficultyXishu(0.5F);
        } else {
            yxyResQues.setDifficultyXishu(0.25F);
        }
        yxyResQues.setDeleteFlag("0");
        yxyResQues.setCreated(new Timestamp(System.currentTimeMillis()));
        yxyResQues.setCreatedBy(questionUploadModel.userId);
        yxyResQues.setModified(new Timestamp(System.currentTimeMillis()));
        yxyResQues.setModifiedBy(questionUploadModel.userId);
        yxyResQues = yxyResQuesRepository.save(yxyResQues);
        yxyResQues.setSycEsFlag(0);
        // 通知es
        EsQuestionUpdateUtil.updateEsQuestion(yxyResQues.getId());
        return yxyResQues.getId();
    }

    public String getBodyDanxuan(QuestionDanXuanUploadModel questionUploadModel) throws JsonProcessingException {
        // 初始化解析器
        JacksonXmlModule jacksonXmlModule = new JacksonXmlModule();
        jacksonXmlModule.setDefaultUseWrapper(true);
        XmlMapper xmlMapper = new XmlMapper(jacksonXmlModule);

        // 初始化模板，sub最外层，stem提干，analysis 解析，comment 评析
        AllTemplate template = new AllTemplate();
        AllTemplate.Sub sub = new AllTemplate.Sub();

        //
        // 题干
        String tigan = questionUploadModel.tigan;
        AllTemplate.Stem stem = new AllTemplate.Stem();
        stem.body = tigan;
        sub.stem = stem;
        //
        // 选项
        // branch选项
        List<AllTemplate.Branch> branchs = new ArrayList<AllTemplate.Branch>();
        List<ChooseModel> chooseModels = questionUploadModel.chooseModels;
        for (ChooseModel chooseModel : chooseModels) {
            AllTemplate.Branch branch = new AllTemplate.Branch();
            branch.no = chooseModel.choose;
            branch.body = content(chooseModel.body);
            branchs.add(branch);
        }
        sub.branch = branchs;
        //
        // answer 答案
        // 多选题 多个answer 答案 逗号隔开 ‘A,B’
        List<AllTemplate.Answer> answers = new ArrayList<AllTemplate.Answer>();
        AllTemplate.Answer answer = new AllTemplate.Answer();
        answer.body = questionUploadModel.daan;
        answers.add(answer);
        sub.answer = answers;

        //
        // 分析
        AllTemplate.Analysis analysis = new AllTemplate.Analysis();
        String fenxi = questionUploadModel.jiexi;
        analysis.body = fenxi;
        sub.analysis = analysis;

        // 放入模版
        template.setSub(sub);
        String xml = xmlMapper.writeValueAsString(template);
        return xml;
    }

    @Override
    public String uploadTianKong(QuestionTianKongUploadModel questionUploadModel) throws JsonProcessingException {
        String body = getBodyTianKong(questionUploadModel);
        String quesId = questionUploadModel.id;
        YxyResQues yxyResQues = getYxyResQues(quesId, questionUploadModel.userId, questionUploadModel.questionType,
                questionUploadModel.phase, questionUploadModel.subject);
        // 知识点
        List<Integer> knowIds = questionUploadModel.knowList.stream().map(x -> x.id).collect(Collectors.toList());
        List<YxyQuesKnow> knows = yxyQuesKnowRepository.findByIdIn(knowIds);
        String knowledgeText = "";
        String knowledgeFullidsString = "";
        for (YxyQuesKnow knowledge : knows) {
            knowledgeText += ("," + knowledge.getName());
            knowledgeFullidsString += ("|" + knowledge.getFullPath());
        }

        yxyResQues.setBody(body);
        yxyResQues.setKnowledgeTexts(knowledgeText);
        List<String> strKnowIds = knowIds.stream().map(x -> x + "").collect(Collectors.toList());
        String strKnowId = StringUtils.join(strKnowIds, ",");
        yxyResQues.setKnowledgeIds(strKnowId);
        yxyResQues.setKnowFullIds(knowledgeFullidsString);

        yxyResQues.setDifficultyLevel(questionUploadModel.difficultyLevel);

        yxyResQues.setSrcType(questionUploadModel.srcType);
        if ("1".equals(questionUploadModel.difficultyLevel)) {
            yxyResQues.setDifficultyXishu(0.75F);
        } else if ("2".equals(questionUploadModel.difficultyLevel)) {
            yxyResQues.setDifficultyXishu(0.5F);
        } else {
            yxyResQues.setDifficultyXishu(0.25F);
        }
        yxyResQues.setDeleteFlag("0");
        yxyResQues.setCreated(new Timestamp(System.currentTimeMillis()));
        yxyResQues.setCreatedBy(questionUploadModel.userId);
        yxyResQues.setModified(new Timestamp(System.currentTimeMillis()));
        yxyResQues.setModifiedBy(questionUploadModel.userId);
        yxyResQues.setSycEsFlag(0);
        yxyResQues = yxyResQuesRepository.save(yxyResQues);
        // 通知es
        EsQuestionUpdateUtil.updateEsQuestion(yxyResQues.getId());
        return yxyResQues.getId();
    }

    public String getBodyTianKong(QuestionTianKongUploadModel questionTianKongUploadModel)
            throws JsonProcessingException {
        // 初始化解析器
        JacksonXmlModule jacksonXmlModule = new JacksonXmlModule();
        jacksonXmlModule.setDefaultUseWrapper(true);
        XmlMapper xmlMapper = new XmlMapper(jacksonXmlModule);

        // 初始化模板，sub最外层，stem提干，analysis 解析，comment 评析
        AllTemplate template = new AllTemplate();
        AllTemplate.Sub sub = new AllTemplate.Sub();

        //
        // 题干
        String tigan = questionTianKongUploadModel.tigan;
        AllTemplate.Stem stem = new AllTemplate.Stem();
        stem.body = tigan;
        sub.stem = stem;
        //
        // answer 答案
        // 多选题 多个answer 答案 逗号隔开 ‘A,B’
        List<AllTemplate.Answer> answers = new ArrayList<AllTemplate.Answer>();
        int i = 1;
        for (String tkanswer : questionTianKongUploadModel.daan) {
            AllTemplate.Answer answer = new AllTemplate.Answer();
            answer.no = i + "";
            answer.body = tkanswer;
            i++;
            answers.add(answer);
        }
        sub.answer = answers;

        //
        // 分析
        AllTemplate.Analysis analysis = new AllTemplate.Analysis();
        String fenxi = questionTianKongUploadModel.jiexi;
        analysis.body = fenxi;
        sub.analysis = analysis;

        // 放入模版
        template.setSub(sub);
        String xml = xmlMapper.writeValueAsString(template);
        return xml;
    }

    @Override
    public String uploadJieDa(QuestionJieDaUploadModel questionUploadModel) throws JsonProcessingException {
        String body = getBodyJieDa(questionUploadModel);
        String quesId = questionUploadModel.id;
        YxyResQues yxyResQues = getYxyResQues(quesId, questionUploadModel.userId, questionUploadModel.questionType,
                questionUploadModel.phase, questionUploadModel.subject);
        // 知识点
        List<Integer> knowIds = questionUploadModel.knowList.stream().map(x -> x.id).collect(Collectors.toList());
        List<YxyQuesKnow> knows = yxyQuesKnowRepository.findByIdIn(knowIds);
        String knowledgeText = "";
        String knowledgeFullidsString = "";
        for (YxyQuesKnow knowledge : knows) {
            knowledgeText += ("," + knowledge.getName());
            knowledgeFullidsString += ("|" + knowledge.getFullPath());
        }

        yxyResQues.setBody(body);
        yxyResQues.setKnowledgeTexts(knowledgeText);

        List<String> strKnowIds = knowIds.stream().map(x -> x + "").collect(Collectors.toList());
        String strKnowId = StringUtils.join(strKnowIds, ",");
        yxyResQues.setKnowledgeIds(strKnowId);
        yxyResQues.setKnowFullIds(knowledgeFullidsString);

        yxyResQues.setDifficultyLevel(questionUploadModel.difficultyLevel);

        yxyResQues.setSrcType(questionUploadModel.srcType);
        if ("1".equals(questionUploadModel.difficultyLevel)) {
            yxyResQues.setDifficultyXishu(0.75F);
        } else if ("2".equals(questionUploadModel.difficultyLevel)) {
            yxyResQues.setDifficultyXishu(0.5F);
        } else {
            yxyResQues.setDifficultyXishu(0.25F);
        }
        yxyResQues.setDeleteFlag("0");
        yxyResQues.setCreatedBy(questionUploadModel.userId);
        yxyResQues.setCreated(new Timestamp(System.currentTimeMillis()));
        yxyResQues.setCreatedBy(questionUploadModel.userId);
        yxyResQues.setModified(new Timestamp(System.currentTimeMillis()));
        yxyResQues.setModifiedBy(questionUploadModel.userId);
        yxyResQues.setSycEsFlag(0);
        yxyResQues = yxyResQuesRepository.save(yxyResQues);
        // 通知es
        EsQuestionUpdateUtil.updateEsQuestion(yxyResQues.getId());
        return yxyResQues.getId();
    }

    public String getBodyJieDa(QuestionJieDaUploadModel questionTianKongUploadModel) throws JsonProcessingException {
        // 初始化解析器
        JacksonXmlModule jacksonXmlModule = new JacksonXmlModule();
        jacksonXmlModule.setDefaultUseWrapper(true);
        XmlMapper xmlMapper = new XmlMapper(jacksonXmlModule);

        // 初始化模板，sub最外层，stem提干，analysis 解析，comment 评析
        AllTemplate template = new AllTemplate();
        AllTemplate.Sub sub = new AllTemplate.Sub();

        //
        // 题干
        String tigan = questionTianKongUploadModel.tigan;
        AllTemplate.Stem stem = new AllTemplate.Stem();
        stem.body = tigan;
        sub.stem = stem;
        //
        // answer 答案
        // 多选题 多个answer 答案 逗号隔开 ‘A,B’
        List<AllTemplate.Answer> answers = new ArrayList<AllTemplate.Answer>();
        AllTemplate.Answer answer = new AllTemplate.Answer();
        answer.body = questionTianKongUploadModel.daan;
        answers.add(answer);
        sub.answer = answers;

        //
        // 分析
        AllTemplate.Analysis analysis = new AllTemplate.Analysis();
        String fenxi = questionTianKongUploadModel.jiexi;
        analysis.body = fenxi;
        sub.analysis = analysis;

        // 放入模版
        template.setSub(sub);
        String xml = xmlMapper.writeValueAsString(template);
        return xml;
    }

    /**
     * 去掉第一个P 标签
     * 
     * @return
     */
    public String content(String body) {
        Document document = Jsoup.parse(body);
        Elements elements = document.getElementsByTag("p");
        if (elements.size() > 0) {
            Element element = elements.get(0);
            element.unwrap();
        }
        return document.getElementsByTag("body").html();
    }

}
